package com.xrf;

import java.io.PrintWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DataManager {
    private static Scanner scanner = new Scanner(System.in);
    
    // 通用的数据操作方法
    public static <T> void addData(List<T> list, DataCreator<T> creator) {
        System.out.println("--------添加数据-------");
        T data = creator.createData();
        list.add(data);
    }
    
    public static <T> void removeData(List<T> list) {
        System.out.println("--------删除数据-------");
        System.out.println("请输入索引：");
        int index = scanner.nextInt();
        if (index >= 0 && index < list.size()) {
            list.remove(index);
            System.out.println("删除成功！");
        } else {
            System.out.println("索引无效！");
        }
    }
    
    public static <T> void displayData(List<T> list) {
        System.out.println("--------数据显示-------");
        for (int i = 0; i < list.size(); i++) {
            System.out.println("索引 " + i + ": " + list.get(i));
        }
    }
    
    public static void writeToFile(List<?> list, String filename) {
        try (PrintWriter pw = new PrintWriter(filename)) {
            for (Object item : list) {
                pw.println(item.toString());
            }
            pw.flush();
            System.out.println("数据已写入文件: " + filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 数据创建器接口
    public interface DataCreator<T> {
        T createData();
    }
}